package com.ruoyi.user.service.impl;

import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.model.user.UserVO;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.service.IUserCacheService;
import com.ruoyi.user.service.IUserService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;

@Service
public class UserCacheServiceImpl implements IUserCacheService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IUserService userService;

    @Override
    public void login(String token, Long userId) {
        redisCache.setCacheObject(String.format(Constants.USER_TOKEN,token),userId,180, TimeUnit.DAYS);
    }

    @Override
    public UserVO getUser(String token) {
        Object objId = redisCache.getCacheObject(String.format(Constants.USER_TOKEN,token));
        if(ObjectUtil.isNull(objId)){
            return null;
        }

        String cacheLoginUser = String.format(Constants.USER_LOGIN_INFO,objId);
        Object objUser = redisCache.getCacheObject(cacheLoginUser);
        if(ObjectUtil.isNotNull(objUser)){
            return (UserVO) objUser;
        }

        User user = userService.getById(Long.valueOf(objId.toString()));
        if(ObjectUtil.isNull(user)){
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user,userVO);
        redisCache.setCacheObject(cacheLoginUser,userVO,1,TimeUnit.HOURS);
        return userVO;
    }
}
